package com.weixin.servlet.backstage;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.weixin.service.IBackstageService;
import com.weixin.service.impl.BackstageServiceImpl;
import com.weixin.vo.Admin;
import com.weixin.vo.AdminEdit;
import com.weixin.vo.AdminList;
import com.weixin.vo.Role;

/**
 * servlet，处理角色管理页面
 * @author 唐鑫明
 *
 */
@WebServlet("/BackstageRoleServlet/*")
public class BackstageRoleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	boolean b = false;
    IBackstageService backstageService = new BackstageServiceImpl();
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pathInfo = request.getPathInfo().substring(1);
		if("listAdminInfo".equals(pathInfo)) {
			listAdminInfo(request,response);
		}else if("editAdminState".equals(pathInfo)) {
			editAdminState(request,response);
		}else if("preAddAdmin".equals(pathInfo)) {
			preAddAdmin(request,response);
		}else if("addAdmin".equals(pathInfo)) {
			addAdmin(request, response);
		}else if("editAdmin".equals(pathInfo)) {
			editAdmin(request,response);
		}else if("preEditAdmin".equals(pathInfo)) {
			preEditAdmin(request,response);
		}else if("deleteAdmin".equals(pathInfo)) {
			deleteAdmin(request,response);
		}else if("deleteSelectAdmin".equals(pathInfo)) {
			deleteSelectAdmin(request,response);
		}else if("resetAdminPass".equals(pathInfo)) {
			resetAdminPass(request,response);
		}else if("resetSelectAdminPass".equals(pathInfo)) {
			resetSelectAdminPass(request,response);
		}else if("accountYanZheng".equals(pathInfo)) {
			accountYanZheng(request,response);
		}
	}
	/**
	 * 账号验证
	 * @param request
	 * @param response
	 */
	private void accountYanZheng(HttpServletRequest request, HttpServletResponse response) {
		String admin_account = null;
		if(request.getParameter("admin_account")!=null&&!(request.getParameter("admin_account").equals(""))) {
			admin_account = request.getParameter("admin_account");
		}
		try {
			//调用业务层的方法查找数据库中是否存在该账号
			Admin admin = backstageService.selectAdminByAccount(admin_account);
			if(admin!=null) {
				//将数据传到前段页面
				response.getWriter().println(1);
			}else {
				//将数据传到前段页面
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 初始化选中管理员的密码
	 * @param request
	 * @param response
	 */
	private void resetSelectAdminPass(HttpServletRequest request, HttpServletResponse response) {
			String[] admin_ids = request.getParameterValues("admin_id");
			try {
				//调用业务层的方法初始化选中管理员的密码
				boolean b = backstageService.resetSeletAdminPass(admin_ids);
				if(b) {
					response.getWriter().println(1);
				}else {
					response.getWriter().println(0);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	/**
	 * 初始化单个管理员的密码
	 * @param request
	 * @param response
	 */
	private void resetAdminPass(HttpServletRequest request, HttpServletResponse response) {
		int admin_id = 0;
		if(request.getParameter("admin_id")!=null&&!(request.getParameter("admin_id").equals("")) ) {
			admin_id = Integer.valueOf(request.getParameter("admin_id"));
		}
		try {
			//调用业务层的方法根据ID初始化对应管理员的密码
			boolean b = backstageService.resetAdminPass(admin_id);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 删除选中的管理员信息
	 * @param request
	 * @param response
	 */
	private void deleteSelectAdmin(HttpServletRequest request, HttpServletResponse response) {
			String[] admin_ids = request.getParameterValues("admin_id");
			try {
				//调用业务层的方法删除选中管理员ID
				boolean b = backstageService.deleteSelectAdmin(admin_ids);
				if(b) {
					response.getWriter().println(1);
				}else {
					response.getWriter().println(0);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	/**
	 * 删除单个管理员
	 * @param request
	 * @param response
	 */
	private void deleteAdmin(HttpServletRequest request, HttpServletResponse response) {
		int admin_id = 0;
		if(request.getParameter("admin_id")!=null&&!(request.getParameter("admin_id").equals(""))) {
			admin_id  = Integer.valueOf(request.getParameter("admin_id"));
		}
		
		try {
			//调用业务层的方法根据ID删除对应管理员的信息
			boolean b = backstageService.deleteAdmin(admin_id);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 预修改管理员信息
	 * @param request
	 * @param response
	 */
	private void preEditAdmin(HttpServletRequest request, HttpServletResponse response) {
		//设置编码
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		int admin_id = 0;
		if(request.getParameter("admin_id")!=null&&!(request.getParameter("admin_id").equals(""))) {
			admin_id = Integer.valueOf(request.getParameter("admin_id"));
		}
		try {
			//调用业务层的方法根据ID查询对应管理员的信息
			AdminList adminById = backstageService.selectAdminById(admin_id);
			Date date = adminById.getAdmin_time();
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
			//将数据传到role_edit.jsp页面
			response.getWriter().println("["+new Gson().toJson(adminById)+","+new Gson().toJson(time)+"]");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 管理员信息修改
	 * @param request
	 * @param response
	 */
	private void editAdmin(HttpServletRequest request, HttpServletResponse response) {
		// 设置编码
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		// 创建管理员对象
		AdminEdit aEdit = new AdminEdit();
		int admin_id = 0;
		if (request.getParameter("admin_id") != null && !("".equals(request.getParameter("admin_id")))) {
			admin_id = Integer.valueOf(request.getParameter("admin_id"));
		}
		String admin_account = null;
		if (request.getParameter("admin_account") != null && !("".equals(request.getParameter("admin_account")))) {
			admin_account = request.getParameter("admin_account");
		}
		String admin_name = null;
		if (request.getParameter("admin_name") != null && !("".equals(request.getParameter("admin_name")))) {
			admin_name = request.getParameter("admin_name");
		}
		String admin_pwd = null;
		if (request.getParameter("admin_pwd") != null && !("".equals(request.getParameter("admin_pwd")))) {
			admin_pwd = request.getParameter("admin_pwd");
		}
		String role_id = null;
		if (request.getParameter("role_id") != null && !("".equals(request.getParameter("role_id")))) {
			role_id = request.getParameter("role_id");
		}
		int state_id = 0;
		if (request.getParameter("state_id") != null && !("".equals(request.getParameter("state_id")))) {
			state_id = Integer.valueOf(request.getParameter("state_id"));
		}
		String admin_create = null;
		if (request.getParameter("admin_create") != null && !("".equals(request.getParameter("admin_create")))) {
			admin_create = request.getParameter("admin_create");
		}
		Date admin_time = null;
		if (request.getParameter("admin_time") != null && !("".equals(request.getParameter("admin_time")))) {
			try {
				admin_time = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").parse(request.getParameter("admin_time"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		aEdit.setAdmin_account(admin_account);
		aEdit.setAdmin_create(admin_create);
		aEdit.setAdmin_id(admin_id);
		aEdit.setAdmin_img(null);
		aEdit.setAdmin_name(admin_name);
		aEdit.setAdmin_pwd(admin_pwd);
		aEdit.setRole_id(role_id);
		aEdit.setState_id(state_id);
		try {
			// 根据编号查询管理员的信息
			AdminList admin = backstageService.selectAdminById(admin_id);
			// 判断是否修改时间，如果修改则不动，否则修改为当前时间
			if (!admin.getAdmin_time().equals(admin_time)) {
				aEdit.setAdmin_time(new Date());
			} else {
				aEdit.setAdmin_time(admin_time);
			}
			// 调用业务层的方法根据ID修改管理员信息
			boolean b = backstageService.editAdmin(aEdit);
			if (b) {
				response.getWriter().println(1);
			} else {
				response.getWriter().println(0);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 添加管理员方法
	 * @param request
	 * @param response
	 */
	private void addAdmin(HttpServletRequest request, HttpServletResponse response) {
		//设置编码
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//创建管理员对象
		AdminEdit aEdit = new AdminEdit();
		String admin_account = null;
		if(request.getParameter("admin_account")!=null&&!("".equals(request.getParameter("admin_account")))) {
			admin_account = request.getParameter("admin_account");
		}
		String admin_name = null;
		if(request.getParameter("admin_name")!=null&&!("".equals(request.getParameter("admin_name")))) {
			admin_name = request.getParameter("admin_name");
		}
		String admin_pwd = null;
		if(request.getParameter("admin_pwd")!=null&&!("".equals(request.getParameter("admin_pwd")))) {
			admin_pwd = request.getParameter("admin_pwd");
		}
		String role_id = null;
		if(request.getParameter("role_id")!=null&&!("".equals(request.getParameter("role_id")))) {
			role_id = request.getParameter("role_id");
		}
		int state_id = 0;
		if(request.getParameter("state_id")!=null&&!("".equals(request.getParameter("state_id")))) {
			state_id = Integer.valueOf(request.getParameter("state_id"));
		}
		String admin_create = null;
		if(request.getParameter("admin_create")!=null&&!("".equals(request.getParameter("admin_create")))) {
			admin_create = request.getParameter("admin_create");
		}
		aEdit.setAdmin_account(admin_account);
		aEdit.setAdmin_create(admin_create);
		aEdit.setAdmin_img(null);
		aEdit.setAdmin_name(admin_name);
		aEdit.setAdmin_pwd(admin_pwd);
		aEdit.setAdmin_time(new Date());
		aEdit.setRole_id(role_id);
		aEdit.setState_id(state_id);
		try {
			//调用业务层的方法根据账号查找数据库中是否存在该用户
			Admin adminByAccount = backstageService.selectAdminByAccount(admin_account);
			if(adminByAccount!=null) {
				response.getWriter().println(2);
			}else {
				//调用业务层的方法增加管理员
			    b = backstageService.addAdmin(aEdit);
				if(b) {
					response.getWriter().println(1);
				}else {
					response.getWriter().println(0);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 预添加管理员方法
	 * @param request
	 * @param response
	 */
	private void preAddAdmin(HttpServletRequest request, HttpServletResponse response) {
		//设置编码
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		try {
			//调用业务层的方法查询角色信息
			List<Role> roleList = backstageService.selectRole();
			//将数据传递到role_add.jsp页面
			response.getWriter().println(new Gson().toJson(roleList));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 管理员的启用与禁用
	 * @param request
	 * @param response
	 */
	private void editAdminState(HttpServletRequest request, HttpServletResponse response) {
		int state_id = 0;
		if(request.getParameter("state_id")!=null&&!(request.getParameter("state_id").equals(""))) {
			state_id = Integer.valueOf(request.getParameter("state_id"));
		}
		int admin_id = 0;
		if(request.getParameter("admin_id")!=null&&!(request.getParameter("admin_id").equals(""))) {
			admin_id = Integer.valueOf(request.getParameter("admin_id"));
		}
		try {
			//调用业务层的方法修改管理员状态
			boolean b = false;
			if(state_id==1) {
				 b = backstageService.editAdminState(admin_id, 2);
			}else {
				 b = backstageService.editAdminState(admin_id, 1);
			}
			
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 显示角色信息
	 * @param request
	 * @param response
	 */
	private void listAdminInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String admin_name= null;
		if(request.getParameter("admin_name")!=null&&!(request.getParameter("admin_name").equals(""))) {
			admin_name = request.getParameter("admin_name");
		}
		int pageNum = 1;
		if(request.getParameter("pageNum")!=null&&!(request.getParameter("pageNum").equals(""))) {
			pageNum = Integer.valueOf(request.getParameter("pageNum"));
		}
		int pageSize = 6;
		try {
			//调用业务层的方法获取管理员信息
			List<AdminList> adminInfoList = backstageService.selectAdminInfo(admin_name,pageNum,pageSize);
			//调用业务层的方法查询管理员的人数
			int count = (int) backstageService.selectAdminCount(admin_name);
			//计算总页数
			int pageCount = (int)Math.ceil(count*1.0/pageSize);
			//request绑定属性
			request.setAttribute("adminInfoList",adminInfoList);
			request.setAttribute("admin_name",admin_name);
			request.setAttribute("pageNum", pageNum);
			request.setAttribute("pageCount", pageCount);
			//跳转到role_list.jsp页面展示数据
			request.getRequestDispatcher("/pages/houtai/role/role_list.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
